package com.xuxin.baby.activity;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.entity.LocalMedia;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.xuxin.baby.R;
import com.xuxin.baby.base.BaseActivity;
import com.xuxin.baby.base.BaseConstant;
import com.xuxin.baby.bean.BaseBean;
import com.xuxin.baby.bean.UploadFilesBean;
import com.xuxin.baby.contract.UploadFilesContract;
import com.xuxin.baby.contract.UserChildDataContract;
import com.xuxin.baby.event.MainFragmentEvent;
import com.xuxin.baby.glide.GlideApp;
import com.xuxin.baby.network.Retrofit;
import com.xuxin.baby.photo.PhotoUtils;
import com.xuxin.baby.popup.GestationalPopup;
import com.xuxin.baby.presenter.UploadFilesPresenter;
import com.xuxin.baby.presenter.UserChildDataPresenter;
import com.xuxin.baby.utils.ACache;
import com.xuxin.baby.utils.DatePickerUtils;
import com.xuxin.baby.utils.PathUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by xu_xin
 * Created on 2020.08.10 0010
 * 宝宝信息
 */
public class UserChildDataActivity extends BaseActivity implements UserChildDataContract.View, UploadFilesContract.View {
    private final UserChildDataContract.Presenter presenter = new UserChildDataPresenter(this);
    private final UploadFilesContract.Presenter presenter2 = new UploadFilesPresenter(this);
    RequestOptions options = RequestOptions.bitmapTransform(new CircleCrop());
    @BindView(R.id.title_left)
    ImageView title_left;
    @BindView(R.id.title_right)
    ImageView title_right;
    @BindView(R.id.title_name)
    TextView title_name;
    @BindView(R.id.button)
    Button button;
    @BindView(R.id.user_child_data_image)
    ImageView user_child_data_image;//头像
    @BindView(R.id.user_child_data_name)
    EditText user_child_data_name;//昵称
    @BindView(R.id.user_child_data_birthday)
    TextView user_child_data_birthday;//生日
    @BindView(R.id.user_child_gestational)
    TextView user_child_gestational;
    @BindView(R.id.user_child_data_gender)
    TextView user_child_data_gender;//性别
    @BindView(R.id.user_child_data_height)
    EditText user_child_data_height;//身高
    @BindView(R.id.user_child_data_weight)
    EditText user_child_data_weight;//体重
    @BindView(R.id.user_child_data_head)
    EditText user_child_data_head;//头围

    private String memberId;//用户id
    private String tenantId;//租户id
    private String token;//授权token

    private String childId;
    private String avatar;//头像
    private String nickname;//昵称
    private String birthday;//生日
    private String sex;//性别
    private String height;//身高
    private String weight;//体重
    private String headCircle;//头围

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_user_child_data);
    }

    @Override
    public void initView() {
        title_name.setText("宝宝信息");
        button.setText("保存");
    }

    @Override
    public void initData() {
        ACache aCache = ACache.get(this);
        memberId = aCache.getAsString(BaseConstant.memberId);
        tenantId = aCache.getAsString(BaseConstant.tenantId);
        token = aCache.getAsString(BaseConstant.token);
        childId = getIntent().getStringExtra("childId");
        if (!StringUtils.isEmpty(childId)) {//修改
            avatar = getIntent().getStringExtra("avatar");
            nickname = getIntent().getStringExtra("nickname");
            birthday = getIntent().getStringExtra("birthday");
            sex = getIntent().getStringExtra("sex");
            height = getIntent().getStringExtra("height");
            weight = getIntent().getStringExtra("weight");
            headCircle = getIntent().getStringExtra("headCircle");
            String image = Retrofit.image_url + avatar;
            GlideApp.with(context).load(image).placeholder(R.mipmap.img_placeholder_head).apply(options).into(user_child_data_image);
            user_child_data_name.setText(nickname);
            user_child_data_birthday.setText(birthday);
            user_child_data_gender.setText(sex);
            user_child_data_height.setText(height);
            user_child_data_weight.setText(weight);
            user_child_data_head.setText(headCircle);
        }
    }

    @Override
    public void onComplete() {
        dismiss();
    }

    @Override
    @OnClick({R.id.title_left, R.id.user_child_data_image_update,
            R.id.user_child_data_birthday, R.id.user_child_gestational,
            R.id.user_child_data_gender, R.id.button})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.title_left) {
            finish();
        } else if (id == R.id.user_child_data_image_update) {
            PhotoUtils.openPhoto(this, new PhotoUtils.OnResultListener() {
                @Override
                public void onResult(List<LocalMedia> result) {
                    takePhoto(result);
                }
            });
        } else if (id == R.id.user_child_data_birthday) {
            DatePickerUtils.showDate(this, new DatePickerUtils.onListener() {
                @Override
                public void onShow(String time) {
                    user_child_data_birthday.setText(time);
                }
            });
        } else if (id == R.id.user_child_gestational) {
            new XPopup.Builder(context)
                    .dismissOnTouchOutside(true)
                    .asCustom(new GestationalPopup(context, new GestationalPopup.OnClickListener() {
                        @Override
                        public void onGestational(String week, String day) {
                            user_child_gestational.setText(week + day);
                        }
                    }))
                    .show();
        } else if (id == R.id.user_child_data_gender) {
            new XPopup.Builder(context)
                    .maxWidth((int) (ScreenUtils.getScreenWidth() * 0.6))
                    .asCenterList("请选择宝宝性别", new String[]{"男宝宝", "女宝宝"},
                            new OnSelectListener() {
                                @Override
                                public void onSelect(int position, String text) {
                                    if (position == 0) {
                                        user_child_data_gender.setText("男");
                                    } else {
                                        user_child_data_gender.setText("女");
                                    }

                                }
                            })
                    .show();
        } else if (id == R.id.button) {
            nickname = user_child_data_name.getText().toString().trim();//昵称
            birthday = user_child_data_birthday.getText().toString().trim();//生日
            sex = user_child_data_gender.getText().toString().trim();//性别
            height = user_child_data_height.getText().toString().trim();//身高
            weight = user_child_data_weight.getText().toString().trim();//体重
            headCircle = user_child_data_head.getText().toString().trim();//头围
            if (StringUtils.isEmpty(nickname)) {
                ToastUtils.showShort("请输入昵称");
            } else if (StringUtils.isEmpty(birthday)) {
                ToastUtils.showShort("请输入出生日期");
            } else if (StringUtils.isEmpty(sex)) {
                ToastUtils.showShort("请选择性别");
            } else if (StringUtils.isEmpty(height) || Double.parseDouble(height) == 0) {
                ToastUtils.showShort("请输入身高");
            } else if (StringUtils.isEmpty(weight) || Double.parseDouble(weight) == 0) {
                ToastUtils.showShort("请输入体重");
            } else if (StringUtils.isEmpty(headCircle) || Double.parseDouble(headCircle) == 0) {
                ToastUtils.showShort("请输入头围");
            } else if (null != parts && parts.size() > 0) {
                popup.show();
                handler.sendEmptyMessage(0);
            } else {
                popup.show();
                handler.sendEmptyMessage(1);
            }
        }
    }


    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 0:
                    presenter2.uploadFiles(tenantId, token, memberId, "Edu_Children", "avatar", parts);
                    break;
                case 1:
                    if (StringUtils.isEmpty(childId)) {
                        //添加宝宝
                        presenter.addUserChild(tenantId,
                                token,
                                memberId,
                                avatar,
                                nickname,
                                birthday,
                                sex,
                                height,
                                weight,
                                headCircle);
                    } else {
                        //修改宝宝
                        presenter.updateUserChild(tenantId,
                                token,
                                childId,
                                memberId,
                                avatar,
                                nickname,
                                birthday,
                                sex,
                                height,
                                weight,
                                headCircle);
                    }

                case 2:
                    break;
            }
            return false;
        }
    });

    @Override
    public void onSuccess(BaseBean baseBean) {
        EventBus.getDefault().post(new MainFragmentEvent());
        setResult(200);
        finish();
    }

    @Override
    public void onSuccess(UploadFilesBean uploadFilesBean) {
        avatar = uploadFilesBean.getResult();
        handler.sendEmptyMessage(1);
    }

    private List<MultipartBody.Part> parts;

    public void takePhoto(List<LocalMedia> result) {
        LocalMedia media = result.get(0);
        String path = media.isCompressed() ? media.getCompressPath() : media.getPath();
        GlideApp.with(context).load(path).placeholder(R.mipmap.img_placeholder_head).apply(options).into(user_child_data_image);
        File file = new File(path);
        RequestBody requestBody = RequestBody.create(file, MediaType.parse("image/jpeg"));
        parts = new ArrayList<>();
        parts.add(MultipartBody.Part.createFormData("files", PathUtils.getImageName(), requestBody));
    }
}